package com.nku.mason.lucene.fy.dao;

import java.util.ArrayList;
import java.util.List;

import org.apache.lucene.document.Document;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;

import com.nku.mason.lucene.fy.vo.Article;
import com.nku.mason.lucene.util.LuceneUtil;

public class ArticleDao {
	/**
	 * 获取匹配关键字的所有记录的个数
	 * @param keyWord 关键字
	 * @return
	 * @throws Exception
	 */
	public int getAllRecord(String keyWord) throws Exception{
		
		IndexSearcher indexSearcher = new IndexSearcher(LuceneUtil.getDirectory());
		QueryParser queryParser = new QueryParser(LuceneUtil.getVersion(), "content", LuceneUtil.getAnalyzer());
		Query query = queryParser.parse(keyWord);
		TopDocs topDocs = indexSearcher.search(query, 100);
		indexSearcher.close();
		return topDocs.totalHits;	//不受search中100的影响
	}
	
	/**
	 * 返回匹配关键字的分页集合
	 * @param keyWord 关键字
	 * @param start 查询起始记录
	 * @param pageSize 页大小
	 * @return 分页集合
	 * @throws Exception
	 */
	public List<Article> findAll(String keyWord,int start,int pageSize) throws Exception{
		List<Article> res = new ArrayList<>();
		
		IndexSearcher indexSearcher = new IndexSearcher(LuceneUtil.getDirectory());
		QueryParser queryParser = new QueryParser(LuceneUtil.getVersion(), "content", LuceneUtil.getAnalyzer());
		Query query = queryParser.parse(keyWord);
		TopDocs topDocs = indexSearcher.search(query, 1000);
		ScoreDoc[] scoreDocs = topDocs.scoreDocs;
		//确定分页时查询的数据条数
		int limit = Math.min(start + pageSize, scoreDocs.length);
		//将当前start开始到limit条记录塞进集合中，返回
		for (int i = start; i < limit; i++) {
			int no = scoreDocs[i].doc;
			Document document = indexSearcher.doc(no);
			Article article = (Article) LuceneUtil.document2JavaBean(document, Article.class);
			res.add(article);
		}
		
		for(Article article : res){
			System.out.println(article);
		}
		System.out.println("-------------------------------------");
		indexSearcher.close();
		
		return res;
	}
}
